/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com.nextel.idioma;

import com.mot.iden.zip.ZipEntry;
import com.mot.iden.zip.ZipInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import pe.com.nextel.http.MensajeHttp;
import pe.com.nextel.http.XMLListener;
import pe.com.nextel.rms.DataInputStreamX;
import pe.com.nextel.rms.RecordStoreInputStream;
import pe.com.nextel.util.HashMap;

/**
 *
 * @author wpalacios
 */
public class IdiomaManager {

    private final static IdiomaManager bean = new IdiomaManager();
    public final HashMap hasMap = new HashMap();

    //public final static String NOMBRE = "NOMBRE";

    //***** MVCUSUARIO *****
    public final static String JAVA_USUARIO = "JAVA_USUARIO";
    public final static String JAVA_CLAVE = "JAVA_CLAVE";   
    public final static String JAVA_CONFIGURACION = "JAVA_CONFIGURACION";
    public final static String JAVA_INGRESO = "JAVA_INGRESO";

    //***** MVCMENU *****
    public final static String JAVA_INICIAR = "JAVA_INICIAR";
    public final static String JAVA_SINCRONIZAR = "JAVA_SINCRONIZAR";
    public final static String JAVA_LISTAR_CUENTA = "JAVA_LISTAR_CUENTA";
    public final static String JAVA_ENVIOS = "JAVA_ENVIOS";
    
    public final static String JAVA_TITULO = "JAVA_TITULO";



    //MVCREPORTE
    public final static String JAVA_TOTAL = "JAVA_TOTAL";
    public final static String JAVA_ATENDIDO = "JAVA_ATENDIDO";


    //MVCRUTADETALLE - MVCESTADO
    public final static String JAVA_NO_VISITA = "JAVA_NO_VISITA";

    //MVCESTADO
    public final static String JAVA_FOTO = "JAVA_FOTO";
    public final static String JAVA_PRINCIPAL = "JAVA_PRINCIPAL";
    public final static String JAVA_ESTADO = "JAVA_ESTADO";

    //MVCENTREGA
    public final static String JAVA_ENTREGA = "JAVA_ENTREGA";

    //MVCMOTIVO
    public final static String JAVA_MOTIVO = "JAVA_MOTIVO";
   
    //MVCRUTABUSQUEDA
    public final static String JAVA_NO_ATENDIDO = "JAVA_NO_ATENDIDO";
    public final static String JAVA_BUSCAR_RUTAS = "JAVA_BUSCAR_RUTAS";

    //MVCRUTABUSQUEDA - RUTADETALLE
    public final static String JAVA_NOMBRE = "JAVA_NOMBRE";
    public final static String JAVA_CODIGO = "JAVA_CODIGO";
    public final static String JAVA_DETALLE = "JAVA_DETALLE";    
    public final static String JAVA_RUTA = "JAVA_RUTA";  
    public final static String JAVA_TOMAR = "JAVA_TOMAR";

    
    //*****BOTONES DE MENU DE APLICACION*****
    public final static String JAVA_ENVIAR = "JAVA_ENVIAR";
    public final static String JAVA_AVANCE = "JAVA_AVANCE";
    public final static String JAVA_SEGUIR = "JAVA_SEGUIR";
    public final static String JAVA_GRABAR = "JAVA_GRABAR";
    public final static String JAVA_ATRAS = "JAVA_ATRAS";
    public final static String JAVA_SALIR = "JAVA_SALIR";
    public final static String JAVA_BUSCAR = "JAVA_BUSCAR";
    public final static String JAVA_MENU_AYUDA = "JAVA_MENU_AYUDA";

    //*****REFACTOR**
    public final static String JAVA_CANCELAR = "JAVA_CANCELAR";
    public final static String JAVA_SELECCION = "JAVA_SELECCION";
    public final static String JAVA_SI = "JAVA_SI";
    public final static String JAVA_NO = "JAVA_NO";
    public final static String JAVA_VERSION = "JAVA_VERSION";
     public final static String JAVA_MENSAJE = "JAVA_MENSAJE";


    //*******CONTROl RUTA
    public final static String JAVA_ACTIVIDAD_COMPLETA =  "JAVA_ACTIVIDAD_COMPLETA";
    public final static String JAVA_NO_ENCONTRARON_RESULTADOS = "JAVA_NO_ENCONTRARON_RESULTADOS";
    public final static String JAVA_DEBE_SINCRONIZAR = "JAVA_DEBE_SINCRONIZAR";
    public final static String JAVA_GENERAL = "JAVA_GENERAL"; 
    public final static String JAVA_ESPERE_PORFAVOR = "JAVA_ESPERE_PORFAVOR";



    //********* CONTROL USUARIO
    public final static String JAVA_USUARIO_PASS_INVALIDO  = "JAVA_USUARIO_PASS_INVALIDO";
    public final static String JAVA_USUARIO_PASS_INVALIDO_CODIGO = "JAVA_USUARIO_PASS_INVALIDO_CODIGO";
    public final static String JAVA_NO_CONEXION_SERVIDOR = "JAVA_NO_CONEXION_SERVIDOR";
    public final static String JAVA_DATA_COMPLETA = "JAVA_DATA_COMPLETA";
    public final static String JAVA_BIENVENIDO = "JAVA_BIENVENIDO";


    //*****MVCAMANTENIMIENNTO
    public final static String JAVA_INGRESE_DATOS = "JAVA_INGRESE_DATOS";
    public final static String JAVA_REGISTRADO = "JAVA_REGISTRADO";
    public final static String JAVA_ATENCION_BORRAR_INFORMACION = "JAVA_ATENCION_BORRAR_INFORMACION";
    public final static String JAVA_ATENCION_ENVIARA_REGISTRO = "JAVA_ATENCION_ENVIARA_REGISTRO";
    public final static String JAVA_INGRESE_CAMPOS = "JAVA_INGRESE_CAMPOS";


    //******CONTROL VISITA
    public final static String JAVA_NO_EXISTEN_DATOS = "JAVA_NO_EXISTEN_DATOS";
    public final static String JAVA_REGISTRO_ACTUALIZADO = "JAVA_REGISTRO_ACTUALIZADO";
    public final static String JAVA_NO_ATENDER_SERVICIO = "JAVA_NO_ATENDER_SERVICIO";
    public final static String JAVA_ENVIO_REGISTRADO = "JAVA_ENVIO_REGISTRADO";
    public final static String JAVA_AYUDA = "JAVA_AYUDA";

    //* nuevos *//
    public final static String JAVA_DESCRIPCION = "JAVA_DESCRIPCION";
    public final static String JAVA_DIRECCION = "JAVA_DIRECCION";


    public XMLListener xmlListener;
    public RMSIdiomaManager rms = new RMSIdiomaManager();
    private final int RMSCANTIDAD = 100;
    public ListenerIdioma listener;

    private IdiomaManager() {
    }

    public static IdiomaManager getInstance() {
        return bean;
    }

    public boolean isDatos() {
        try {
            return rms.cantidadObjectLista(RMSCANTIDAD) > 0;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public synchronized  void registrarSincronizacion(MensajeHttp mensajeHttp) throws Exception {
        try{
        
        procesarSincronizarData(mensajeHttp);

        processDownloadedData();

        levantarIdiomaMemoria();
        
        listener.respuesta( );
        
        }catch(Exception e){e.printStackTrace();}

    }

    public void levantarIdiomaMemoria() throws Exception{
        rms.getlistaIdioma(); 
    }

    private void procesarSincronizarData(MensajeHttp mensajeHttp) throws Exception {
        //#debug
//        System.out.println("data.procesarSincronizar");

        InputStream input = mensajeHttp.getInput();

        xmlListener.print("Espere por favor ...");

        byte[] bufferData = new byte[5120]; //10240 //5120
        int amountData = 0;
        try {
            RecordStore.deleteRecordStore("RS_DOWNLOAD_TMP");
        } catch (RecordStoreException ex) {
//            System.out.println("not found " + ex.getMessage());
        }

        RecordStore rs = null;

        try {

            rs = RecordStore.openRecordStore("RS_DOWNLOAD_TMP", true);

            while ((amountData = input.read(bufferData)) != -1) {

                rs.addRecord(bufferData, 0, amountData);
            }



        } catch (RecordStoreException ex) {
            //   ex.printStackTrace();
            throw ex;
        } catch (IOException ex) {
            //  ex.printStackTrace();
            throw ex;

        } finally {
            try {
                if (rs != null) {
                    rs.closeRecordStore();
                    rs = null;
                }
                bufferData = null;
            } catch (Exception ex) {
                //  System.out.println("final de error = " + ex.getMessage());
            }
        }

    }

    private void processDownloadedData() throws Exception {
        RecordStore rs = null;
        InputStream input = null;
        try {

            rs = RecordStore.openRecordStore("RS_DOWNLOAD_TMP", true);
            input = new RecordStoreInputStream(rs);
            guardarTablas(input);

        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (rs != null) {
                    rs.closeRecordStore();
                    rs = null;
                }
                if (input != null) {
                    input.close();
                    input = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                RecordStore.deleteRecordStore("RS_DOWNLOAD_TMP");
            } catch (RecordStoreException e) {
                e.printStackTrace();
            }
        }
    }

    private void guardarTablas(InputStream input) throws Exception {

        ZipInputStream zipInput = new ZipInputStream(input);
        ZipEntry ze = zipInput.getNextEntry();

        DataInputStreamX dataInput = new DataInputStreamX(zipInput);

        String recordStoreName;
        int recordStoreSize;

        RecordStore rs = null;

        try {

            while (true) {

                recordStoreName = dataInput.readString();
                recordStoreSize = dataInput.readInt();

                System.out.println("recordStoreName=" + recordStoreName + "|");
                xmlListener.print(recordStoreName + " size=" + recordStoreSize);

                rs = RecordStore.openRecordStore(recordStoreName, true);
                saveRecordStore(dataInput, recordStoreSize, rs);

                System.out.println("\t-> RS records: " + rs.getNumRecords());

                rs.closeRecordStore();
                rs = null;

                System.gc();
            }

        } catch (Exception ex) {
            System.out.println(" data terminada: " + ex);

        } finally {
            if (rs != null) {
                rs.closeRecordStore();
            }
        }


        zipInput.closeEntry();

        zipInput.close();

        zipInput = null;

    }

    private void saveRecordStore(DataInputStreamX input, int size, RecordStore rs) throws Exception {
//        System.out.println("saveRecordStore= " + size);
        byte[] buffer = null;
        int dataReaded = 0;
        int bufferSize = 0;

        buffer = new byte[100000];

        while (dataReaded < size) {

            bufferSize = input.readInt();

            input.readFully(buffer, 0, bufferSize);

            rs.addRecord(buffer, 0, bufferSize);

            dataReaded = dataReaded + bufferSize;
            dataReaded += 4;


        }
        buffer = null;

        System.gc();

    }

    public String getMensaje(String param) {
 
//        Iterator iter = hasMap.elements();
//        while(iter.hasNext())
//        {
//            //System.out.println("" + iter.next( ));
//
//        }

        Object cadena = hasMap.get(param);
        
        return cadena == null ? "" : cadena.toString();
        
       
    }

   
}
